package com.rustamg.filedialogs;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.RecyclerView;

import com.apples.hexviewer2.R;

import java.io.File;
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;


/**
 * Created at 30/01/15 21:18
 *
 * @author rustamg
 */
public class FileListAdapter extends RecyclerView.Adapter<FileListAdapter.FileViewHolder> {

    private static final DateFormat sModificationTimeFormat = DateFormat.getDateTimeInstance();
    private final File[] mFiles;
    private final LayoutInflater mInflater;
    private final OnFileSelectedListener mOnFileSelectedListener;

    public FileListAdapter(Context context, File[] files, OnFileSelectedListener fileSelectedListener) {
        if (files == null) {
            throw new IllegalArgumentException("Files list is null. " +
                    "Please make sure that you have read permission to this directory. " +
                    "Have you added android.permission.READ_EXTERNAL_STORAGE permission to your AndroidManifest.xml?");
        }

        mFiles = files;
        mInflater = LayoutInflater.from(context);
        mOnFileSelectedListener = fileSelectedListener;
    }

    @NonNull
    @Override
    public FileViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = mInflater.inflate(R.layout.list_item_file_hex, parent, false);
        return new FileViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final FileViewHolder holder, int position) {
        holder.bind(mFiles[position]);
        holder.getView().setOnClickListener(v -> {
            if (mOnFileSelectedListener != null) {
                FileDialog fileDialog = (FileDialog) mOnFileSelectedListener;
                int ofn = fileDialog.getOFN();
                int maxLen = -1;
                String maxStr = "-1";
                if (ofn == 1) {
                    maxLen = 10485760 * 10;
                    maxStr = "100";
                } else if (ofn == 2) {
                    maxLen = 10485760 * 5;
                    maxStr = "50";
                }
                if (maxLen != -1) {
                    File file = holder.getFile();
                    if (file.length() > maxLen) {
                        String s = v.getContext().getString(R.string.tip_fiel_size_max_10_hex, maxStr);
                        new AlertDialog.Builder(v.getContext())
                                .setCancelable(false)
                                .setMessage(s)
                                .setPositiveButton("确定", null)
                                .create().show();
                        return;
                    }
                }
                mOnFileSelectedListener.onFileSelected(holder.getFile());
            }
        });
    }

    @Override
    public int getItemCount() {
        return mFiles.length;
    }

    public static class FileViewHolder extends RecyclerView.ViewHolder {

        private final View mView;
        private File mFile;

        protected TextView mFileNameText;
        protected TextView mFileModifiedText;
        protected TextView tvFileSize;
        protected ImageView mFileIcon;

        public FileViewHolder(View itemView) {
            super(itemView);
            mView = itemView;
            mFileNameText = (TextView) itemView.findViewById(R.id.tv_file_name);
            mFileModifiedText = (TextView) itemView.findViewById(R.id.tv_file_modified);
            tvFileSize = (TextView) itemView.findViewById(R.id.tv_file_size);
            mFileIcon = (ImageView) itemView.findViewById(R.id.iv_file_icon);
        }

        public void bind(File file) {
            mFile = file;
            if (file.isDirectory()) {
                mFileIcon.setImageResource(R.drawable.ic_folder_hex);
            } else {
                mFileIcon.setImageResource(R.drawable.ic_file_hex);
            }
            mFileNameText.setText(file.getName());
            mFileModifiedText.setText(sModificationTimeFormat.format(new Date(file.lastModified())));
            if (file.isFile()) {
                tvFileSize.setText(formatSize(file.length()));
            } else {
                tvFileSize.setText(null);
            }
        }

        public File getFile() {
            return mFile;
        }

        public View getView() {
            return mView;
        }
    }

    public static String formatSize(long size) {
        if (size <= 0) return "0 B";
        final String[] units = new String[]{"B", "KB", "MB", "GB", "TB"};
        int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
        return String.format(Locale.ENGLISH, "%.2f %s", size / Math.pow(1024, digitGroups), units[digitGroups]);
    }

    public interface OnFileSelectedListener {
        void onFileSelected(File item);
    }
}
